package com.mybatisx.mybatisplus.controller;

import com.alibaba.fastjson.JSON;
import com.mybatisx.mybatisplus.common.response.CommonCode;
import com.mybatisx.mybatisplus.common.response.QueryResponseResult;
import com.mybatisx.mybatisplus.common.response.ResponseResult;
import com.mybatisx.mybatisplus.dto.LeaveDTO;
import com.mybatisx.mybatisplus.dto.SignMessageDTO;
import com.mybatisx.mybatisplus.service.LeaveProcessService;
import lombok.extern.log4j.Log4j2;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.util.json.JSONObject;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuyue
 * @date 2021/9/2 14:31
 */
@RestController
@RequestMapping("/mybatisplus/leaveprocess")
@Log4j2
public class LeaveProcessController {
    /**
     * 流程key值
     */
    public static final String LEAVE_PROCESS = "leaveprocess";

    //获取默认的流程引擎
    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
         @Autowired
     private LeaveProcessService leaveProcessService;
    /**
     * 功能描述: <br>
     * 〈开始请假流程〉
     *
     * @Param: []
     * @Return: com.mybatisx.mybatisplus.common.response.ResponseResult
     * @Author: wuyue
     * @Date: 2021/9/2 14:40
     */
    @PostMapping("/startLeaveProcess")
    public ResponseResult startLeaveProcess(@RequestBody LeaveDTO in) {

        //获取runtimeservice对象
        RuntimeService runtimeService = this.processEngine.getRuntimeService();
        in.setCreateTime(new Date());
        //将信息加入map,以便传入流程中
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("leaveMessage", JSON.toJSONString(in));
        //开启流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(LEAVE_PROCESS, variables);
        //将得到的实例流程id值赋给之前设置的变量
        String processInstanceId = processInstance.getId();
        System.out.println("流程开启成功.......实例流程id:" + processInstanceId);
        return ResponseResult.SUCCESS();
    }


             /**
              * 功能描述: <br>
              * 〈    //开始走流程
              *     //1.获取当前任务,并且完成〉
              * @Param: []
              * @Return: void
              * @Author: wuyue
              * @Date: 2021/9/2 15:10
              */
       @PostMapping("/complete")
    public ResponseResult getTaskAndComplete(@RequestBody SignMessageDTO in){

        //获取taskservice实例
        TaskService taskService = this.processEngine.getTaskService();
        //开始进行流程
    /*    while(this.processEngine.getRuntimeService()
                .createProcessInstanceQuery()//获取查询对象
                .processInstanceId(in.getProcessId())//根据id查询流程实例
                .singleResult()//获取查询结果,如果为空,说明这个流程已经执行完毕,否则,获取任务并执行
                !=null){*/
            Task task = taskService.createTaskQuery()//创建查询对象
                    .processInstanceId(in.getProcessId())//通过流程实例id来查询当前任务
                    .singleResult();//获取单个查询结果
            String taskName = task.getName();
            if(taskName.equals("发起申请")){//职员节点
                completeEmployeeTask(task,in);
            }else if(taskName.equals("领导审批")){//领导节点
                completeLeaderTask(task,in);
            }else{//经理节点
                completeJingliTask(task,in);
            }
      /*  }*/

        System.out.println("同意成功..........");
         return   ResponseResult.SUCCESS();
    }

    //职员提交申请
    public void completeEmployeeTask(Task task,SignMessageDTO signMessageDTO){
        //获取任务id
        String taskId = task.getId();
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("flag",signMessageDTO.getFlag());
        variables.put("suggestion",signMessageDTO.getSuggestion());
        //完成任务
        this.processEngine.getTaskService().complete(taskId,variables);
        System.out.println("职员已经提交申请.......");

    }
    //领导审批
    public void completeLeaderTask(Task task,SignMessageDTO signMessageDTO){
        //获取任务id
        String taskId = task.getId();

        //领导意见
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("flag",signMessageDTO.getFlag());
        variables.put("suggestion",signMessageDTO.getSuggestion());
        //完成任务
        this.processEngine.getTaskService().complete(taskId, variables);
        System.out.println("领导审核完毕........");

    }
    //经理审批
    public void completeJingliTask(Task task,SignMessageDTO signMessageDTO){
        //获取任务id
        String taskId = task.getId();
        String name = task.getName();
        //经理意见
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("flag",signMessageDTO.getFlag());
        variables.put("suggestion",signMessageDTO.getSuggestion());
        //完成任务
        this.processEngine.getTaskService().complete(taskId, variables);
        System.out.println("经理审核完毕........,审核经理:"+name);

    }
       /**
        * 功能描述: <br>
        * 〈获取当前登录人正在执行的请假记录〉
        * @Param: []
        * @Return: com.mybatisx.mybatisplus.common.response.QueryResponseResult
        * @Author: wuyue
        * @Date: 2021/9/3 11:11
        */
         @PostMapping("/getList")
    public QueryResponseResult getList(@RequestBody LeaveDTO in){
        try {
            return  leaveProcessService.getList(in);
        } catch (Exception e) {
            log.error("查询异常[]",e);
            return  new QueryResponseResult(CommonCode.FAIL,null);
        }
    }
    /**
        * 功能描述: <br>
        * 〈获取当前登录人历史的请假记录〉
        * @Param: []
        * @Return: com.mybatisx.mybatisplus.common.response.QueryResponseResult
        * @Author: wuyue
        * @Date: 2021/9/3 11:11
        */
   @PostMapping("/getHistoryList")
    public QueryResponseResult gethistoryList(@RequestBody LeaveDTO in){
        try {
            return  leaveProcessService.getHistoryList(in);
        } catch (Exception e) {
            log.error("查询异常[]",e);
            return  new QueryResponseResult(CommonCode.FAIL,null);
        }
    }


    //获取任务流程图
    @RequestMapping("/getActPlanView")
    public void getActPlanView(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String processInstanceId = request.getParameter("procId");
        try {
            InputStream imageStream = leaveProcessService.getActPlanView(processInstanceId);
            byte[] b = new byte[1024];
            int len;
            while ((len = imageStream.read(b, 0, 1024)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
            response.setContentType("image/png;charset=utf-8");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage(), e);
        }
    }



}
